package com.forhappy.light3ds8.ui;

import android.annotation.SuppressLint;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.forhappy.light3ds8.R;
import com.forhappy.light3ds8.db.LedDBContentProvider;
import com.forhappy.light3ds8.server.ServerIntentService;
@SuppressLint("NewApi")
public class Pg1_get_from_server extends LinearLayout
			implements View.OnClickListener, OnItemClickListener, LoaderCallbacks<Cursor> {
	private static final String TAG = "Pg1_get_from_server";
	public static final int MSG_TAB_DATA_BASIC_ONCHANGE = 1;

	ListView listBasicInfo = null;
	CursorAdapter mAdpater = null;
	Loader<?> mLoader = null;
	ContentObserver observer = null;
	Handler handler = null;
	public Pg1_get_from_server(Context context, AttributeSet attrs ) {
		super(context,attrs);
	}
	public Pg1_get_from_server(Context context) {
		super(context);
		Log.i(TAG, "enter Pg1_get_from_server::Pg1_get_from_server()");
	}


	@Override
	protected void onFinishInflate() {
		Log.i(TAG, "enter Pg1_get_from_server::onFinishInflate()");
		super.onFinishInflate();

	}
	@Override
	protected void onAttachedToWindow() {
		Log.i(TAG, "enter Pg1_get_from_server::onAttachedToWindow()");
		super.onAttachedToWindow();
		
		listBasicInfo = (ListView) findViewById(R.id.LvDataBasic);
		listBasicInfo.setAdapter(initAdapter(null));
		listBasicInfo.setOnItemClickListener(this);
		
		initLoad();
		View bGetBasicDatasFromServer = findViewById(R.id.bGetBasicDatasFromServer);
		bGetBasicDatasFromServer.setOnClickListener(this);
	}
	@Override
	protected void onDetachedFromWindow() {
		Log.i(TAG, "enter Pg1_get_from_server::onDetachedFromWindow()");
		super.onDetachedFromWindow();
		MainUI.getActivity().getLoaderManager().destroyLoader(0);
		if(null != observer){
			getContext().getContentResolver().unregisterContentObserver(observer);
			observer = null;
		}
	}
	@Override
	public void onClick(View v) {
		Log.i(TAG, "enter Pg1_get_from_server::onClick(v:" + v +")");
		switch (v.getId()) {
		case R.id.bGetBasicDatasFromServer:
			ServerIntentService.startService(getContext(), ServerIntentService.CMD_SYNC_DATA_BASIC_INFO, null);
			break;
		default:
			break;
		}
	}

    //举个例子你会理解的更快：X, Y两个listview，X里有1,2,3,4这4个item，Y里有a,b,c,d这4个item。
    //如果你点了b这个item。如下：
	// parent 相当于listview Y适配器的一个指针，可以通过它来获得Y里装着的一切东西，再通俗点就是说告诉你，你点的是Y，不是X - -
	// view 是你点b item的view的句柄，就是你可以用这个view，来获得b里的控件的id后操作控件
	// position 是b在Y适配器里的位置（生成listview时，适配器一个一个的做item，然后把他们按顺序排好队，在放到listview里，意思就是这个b是第position号做好的）
	// id 是b在listview Y里的第几行的位置（很明显是第2行），大部分时候position和id的值是一样的，如果需要的话，你可以自己加个log把position和id都弄出来在logcat里瞅瞅，看了之后心里才踏实。
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Log.i(TAG, "enter Pg1_get_from_server::onItemClick(parent:" + parent +
				",view:" + view + ", position:" + position + ", id:" + id +")");

		TextView isDownload = (TextView) view.findViewById(R.id.tIsDownload);
		if(null == isDownload){
			Log.e(TAG, "load a dataBasic, bu not isDownText, it's invalid!");
			return;
		}
		
		if(!TextUtils.isEmpty(isDownload.getText().toString())){
			Log.d(TAG, "aready download, realData idx = " + isDownload.getText() +
					", set to sendDatas()");
			String str_idx_Download = isDownload.getText().toString();
			int idxRealDatas = Integer.parseInt(str_idx_Download);

//			Pg2_send_to_arm sendToArm = 
////					(Pg2_send_to_arm) MainUI.getActivity().findViewById(R.layout.pg2_send_to_arm);
//			Pg2_send_to_arm sendToArm = 
//					(Pg2_send_to_arm) MainUI.getActivity().findViewById(R.id.pg2_send_to_arm);
//
//			sendToArm.onRealDatasChange(idxRealDatas);
			Pg2_send_to_arm.notifyRealDatasChange(idxRealDatas);
			return;
		}
		
		View vIdx_datas =  view.findViewById(R.id.tIdx_datas);
		if(null == vIdx_datas){
			Log.e(TAG, "load a dataBasic, but not idx_datas, it's invalid!");
			return;
		}
		TextView idx_datas = (TextView) vIdx_datas;
		int idx = -1;
		try{
			String text = idx_datas.getText().toString();
			if(TextUtils.isEmpty(text)){
				Log.e(TAG, "load a dataBasic, but set idx_datas text!!");
				return;
			}
			idx = Integer.parseInt(text);
			Log.d(TAG, "onclick on " + idx + " dataReal");
		} catch(Exception e){
			Log.e(TAG, e.toString(),e);
			return;
		}
		Bundle bd = new Bundle();
		bd.putInt("id", idx);
		ServerIntentService.startService(
				getContext(),
				ServerIntentService.CMD_SYNC_DATA_REAL, bd);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Log.i(TAG, "enter Pg1_get_from_server::onCreateLoader()");
		CursorLoader loader = new CursorLoader(getContext(),
				LedDBContentProvider.URI_DATA_BASIC_INFO_CHECK_REAL,
				null,
				null,
				null,
				"id asc");
		mLoader = loader;
		return loader;
	}


	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		Log.i(TAG, "enter Pg1_get_from_server::onLoadFinished()");
		mAdpater.swapCursor(cursor);
		mAdpater.notifyDataSetChanged();
	}
	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		Log.i(TAG, "enter Pg1_get_from_server::onLoaderReset()");
		mAdpater.swapCursor(null);
	}

	private CursorAdapter initAdapter(final Cursor cursor){
		Log.i(TAG, "enter Pg1_get_from_server::initAdapter()");
		 String[] from = {"_id", "idx_datas", "userName", "isDown", "info"};
		 int[] to = {R.id.tId, R.id.tIdx_datas, R.id.tUserName, R.id.tIsDownload, R.id.tInfo};
		 mAdpater = new SimpleCursorAdapter(
				 getContext(), R.layout.list_show_basic_info,
				 cursor, from, to,
				 SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		 return mAdpater;
	}
	private boolean initLoad(){
		Log.i(TAG, "enter Pg1_get_from_server::initLoad()");
		MainUI.getActivity().getLoaderManager().initLoader(0, null, this);
//		mLoader = MainUI.getActivity().getLoaderManager().getLoader(0);
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				Log.i(TAG, "enter Handler::handleMessage(msg:" + msg + ")");
				super.handleMessage(msg);
				switch (msg.what) {
				case MSG_TAB_DATA_BASIC_ONCHANGE:
					MainUI.getActivity().getLoaderManager().restartLoader(0, null, Pg1_get_from_server.this);
					break;
				default:
					break;
				}
			}
		};

		observer = new ContentObserver(null) {
						@Override
						public void onChange(boolean selfChange, Uri uri) {
							super.onChange(selfChange, uri);
							Log.i(TAG, "enter ContentObserver::onChange()");
							handler.removeMessages(MSG_TAB_DATA_BASIC_ONCHANGE);
							handler.sendEmptyMessageDelayed(MSG_TAB_DATA_BASIC_ONCHANGE, 200);
						}
					};
		getContext().getContentResolver().registerContentObserver(
				LedDBContentProvider.URI_DATA_BASIC_INFO_CHECK_REAL, false,
				observer
				);
		return true;
	}
	
	void onRequestChangeRealDatas(int idxDatas){
		new Thread(){
			@Override
			public void run() {
				
			}
		}.start();
	}
}
